#include "SecondMenuForm.h"
#include <QPainter>
#include <QBrush>
#include <QFont>
#include <QMouseEvent>
#include "NameForm.h"
SecondMenuForm::SecondMenuForm(ElementForm* parent, const int& dispalyNum, const int& top, const int& left)
	:MainMenuForm(nullptr, dispalyNum, top, left), _exitRect(67, 54, 72, 72), _nameRect(145, 78, 259, 24),_name("")
{


}

QString SecondMenuForm::name() const
{
	return _name;
}

void SecondMenuForm::setName(const QString& name)
{
	if (name != _name) {
		_name = name;
		repaint();
	}

}
void SecondMenuForm::setElements(QList<UIElement*> elements)
{
	if (elements.size() == 2) {
		_displayNum = 2;
	}
	else if (elements.size() == 3) {
		_displayNum = 3;
	}else if (elements.size() == 4) {
		_displayNum = 4;
	}
	MainMenuForm::setElements(elements);
}
void SecondMenuForm::paintEvent(QPaintEvent* event)
{
	QPainter painter(this);
	painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing, true);
	CommonFunc::drawFormName(&painter,_nameRect,_name);
	CommonFunc::drawExitBtn(&painter, _exitRect);

	Node<UIElement>* head = _elements.currentNode();
	Node<UIElement>* tail = _elements.currentNode();
	for (int i = 0; i < (_displayNum - 1) / 2; i++) {
		head = head->prev;
		tail = tail->next;
	}
	Node<UIElement>* temp = head;
	while (temp != tail) {
		temp = temp->prev;
		if (temp->data != nullptr) {
			temp->data->setRect(QRect(0, 0, 0, 0)); 
		}
	}
	for (int i = 0; i < _displayNum; i++)
	{
		head = head->next;

		if (head->prev->data != nullptr) {
			if (i < (_displayNum - 1) / 2) {
				head->prev->data->drawElement(this, &painter, false, QRect(_leftDistance + 29, _topDistance + i * 54, 46, 46));
			}
			if (i == (_displayNum - 1) / 2) {
				head->prev->data->drawElement(this, &painter, true, QRect(_leftDistance, _topDistance + i * 54, width() - _leftDistance, 104));
			}
			if (i > (_displayNum - 1) / 2) {
				head->prev->data->drawElement(this, &painter, false, QRect(_leftDistance + 29, _topDistance + (i - 1) * 54 + 112, 46, 46));
			}
		}
	}
	QWidget::paintEvent(event);

}

void SecondMenuForm::mousePressEvent(QMouseEvent* event)
{
	MainMenuForm::mousePressEvent(event);       
}

void SecondMenuForm::mouseMoveEvent(QMouseEvent* event)
{
	MainMenuForm::mouseMoveEvent(event);
}

void SecondMenuForm::mouseReleaseEvent(QMouseEvent* event)
{
	if (_isPressed) {
		if (_exitRect.contains(event->pos()) && _exitRect.contains(_startPos)) {
			longPress();
		}
	}
	MainMenuForm::mouseReleaseEvent(event);
}
